package test5.lupeng.jf.com.teamdemo.homeFragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.IOException;
import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import test5.lupeng.jf.com.teamdemo.R;
import test5.lupeng.jf.com.teamdemo.activitys.LoginActivity;
import test5.lupeng.jf.com.teamdemo.activitys.PersonMessageActivity;
import test5.lupeng.jf.com.teamdemo.activitys.TitleActivity;
import test5.lupeng.jf.com.teamdemo.adapter.MessageAdapter;
import test5.lupeng.jf.com.teamdemo.bean.RequestHome;
import test5.lupeng.jf.com.teamdemo.bean.RequestSend;
import test5.lupeng.jf.com.teamdemo.bean.response.ResponseHome;
import test5.lupeng.jf.com.teamdemo.untils.HTTPUtils;

/**
 * Created by snownight on 2017/7/27.
 */

public class OtherMessageFragment extends Fragment {

    private static final String TAG = "OtherMessageFragment";
    ArrayList<ResponseHome.ResultBean> results;
    MessageAdapter adapter;
    private RecyclerView otherVp;
    private IntentFilter intentFilter;
    private LocalBroadcastManager manager;
    private OmReceiver receiver;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.item_othermessage, container, false);
        return view;
    }

    @Override
    public void onViewCreated(final View view, @Nullable Bundle savedInstanceState) {
        otherVp = view.findViewById(R.id.otherVp);

        //注册
        if (!EventBus.getDefault().isRegistered(this))
        {
            EventBus.getDefault().register(this);
        }

        intentFilter = new IntentFilter();
        intentFilter.addAction("SEND_MESSAGE");
        manager = LocalBroadcastManager.getInstance(view.getContext());
        receiver = new OmReceiver();
        manager.registerReceiver(receiver,intentFilter);


        results = new ArrayList<>();
        RequestDate();
        adapter = new MessageAdapter(results);
        otherVp.setLayoutManager(new LinearLayoutManager(view.getContext()));
        otherVp.setAdapter(adapter);

        //点击头像到个人信息界面；
        adapter.setInterface(new MessageAdapter.MessageInterface() {
            @Override
            public void requestUserMessage(String userId) {
                SharedPreferences sp2 = getActivity().getSharedPreferences("LoginStatus",getActivity().MODE_PRIVATE);

                Boolean isLogining = sp2.getBoolean("isLogin", false);
                if(isLogining){
                    Intent intent = new Intent(view.getContext(), PersonMessageActivity.class);
                    intent.putExtra("userId", userId);
                    startActivityForResult(intent,1);
                }else{
                    //跳转登录界面
                    Intent intent = new Intent(view.getContext(), LoginActivity.class);
                    startActivity(intent);
                }

            }

            @Override
            public void clickToTitle(String content, String articleId, int count1, int count2,Boolean isLikeSizeStatus) {
                //点击进入文章界面
                Intent intent = new Intent(view.getContext(), TitleActivity.class);
                intent.putExtra("articleId", articleId);
                intent.putExtra("articleType", 3);
                intent.putExtra("content", content);
                intent.putExtra("count1", count1);
                intent.putExtra("count2", count2);
                intent.putExtra("isLikeSizeStatus", isLikeSizeStatus);
                startActivityForResult(intent,2);
            }

        });

    }


    public void RequestDate(){
        SharedPreferences sp = getActivity().getSharedPreferences("config", getActivity().MODE_PRIVATE);
        String userId = sp.getString("objectId","0");
        Log.e(TAG, "RequestDate:  objectId "+userId );
        RequestHome object;

        //判断是否为登录状态
        if(userId.equals("0")){
            Log.e(TAG, "啦啦啦啦啦");
            object = new RequestHome("",10,0+"",3+"");
        }else{
            Log.e(TAG, "哈哈哈哈哈哈");
            object = new RequestHome(userId,10,0+"",3+"");
        }

        String url = "https://leancloud.cn/1.1/functions/getJfInfoList";
        Request request = HTTPUtils.requestPost(object, url);
        OkHttpClient client = new OkHttpClient();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                Log.e(TAG, "onResponse: "+result);
                ResponseHome bean = new Gson().fromJson(result, ResponseHome.class);
                results.clear();
                //将所有的数据添加到results集合中；
                results.addAll(bean.getResult());


                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        adapter.notifyDataSetChanged();
                    }
                });
            }


        });


    }


    //广播接收器
    public class OmReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            //接收到广播后刷新主界面；
            RequestDate();
        }
    }

    @Subscribe
    public void onEvent(String string){

        System.out.println("哈哈哈接收到了："+string);
        RequestDate();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        manager.unregisterReceiver(receiver);
        EventBus.getDefault().unregister(this);

    }
}
